<?php
namespace app\api\model;

use app\common\helper\Obj2Array;
use app\common\model\project_model\BlessingCategoryModel;
use app\common\model\project_model\BlessingModel as Blessing;
use think\Exception;

class BlessingModel extends Blessing {

    const PAGE_NUM = 3; // 首页每页分类数目

    public static $error_msg = '';

    /**
     * 通过祝福分类的分页数取得对应分类下的所有祝福
     *
     * @param int $page
     * @return false|array
     * @throws Exception
     */
    public function cateByPage($page = 1) {
        $cateM = new BlessingCategoryModel();
        $cate_ids = $cateM
            ->field(['id'])
            ->order(['sort' => "ASC"])
            ->where(['status' => self::STATUS_OK])
            ->page($page, self::PAGE_NUM)
            ->column('id');
        if (empty($cate_ids)) {
            self::$error_msg = '没有更新的数据了';
            return false;
        }
        return $bless_list = $this->getBlessListByCate($cate_ids);
    }

    /**
     * 获取分类下的祝福
     * @param array $cate 分类id
     * @return false|array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getBlessListByCate($cate) {
        $blessM = new self();
        $bless = $blessM // 分类下的所有bless
            ->field('id, cate_id, cate_name, title, thumb_url')
            ->where('cate_id', 'IN', $cate)
            ->where(['status' => self::STATUS_OK])
            ->order(['sort' => "ASC"])
            ->select();
        // 组织数据
        if (empty($bless)) {
            self::$error_msg = '没有更新的数据了';
            return false;
        }
        return $list = $this->formatBlessing($cate, $bless);
    }

    // 格式化数据
    private function formatBlessing($cate, $bless) {
        $list = [];
        $i = 0;
        foreach ($cate as $cid) {
            foreach ($bless as $item) {
                if ($cid == $item['cate_id']) {
                    $list[$i]['cate_id'] = $cid;
                    $list[$i]['cate_title'] = $item['cate_name'];
                    $list[$i]['list'][] = [
                        'id' => $item['id'],
                        'thumb_url' => $item['thumb_url'],
                        'title' => $item['title'],
                    ];
                }
            }
            if (isset($list[$i])) {
                $i++;
            }

        }
        return $list;
    }


    /**
     * 详情
     *
     * @param $Blessing_id
     * @param $nick_name
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail($Blessing_id, $nick_name) {
        $Blessing = $this->field(['cate_id', 'cate_name', 'updated_time', 'status', 'music_title', 'sort'], true)->where(['id' => $Blessing_id])->find();
        $data = $Blessing;
        $data['content'] = $this->formatContent($data['content'], $nick_name);
        $data['share_title'] = str_replace('###nickname###', $nick_name, $data['share_title']);
        return $data;
    }

    /**
     * 格式化
     * @param $content
     * @param $nick_name
     * @return string
     */
    private function formatContent($content, $nick_name) {
        $content = htmlspecialchars($content);
        file_put_contents(__DIR__ . DS . 'content.txt', date('Y-m-d H:i:s', time()) . PHP_EOL . $content . PHP_EOL);
        $content = str_replace('###nickname###', $nick_name, $content);
        //$content = str_replace('&nbsp;', chr(32), $content);
        return $content ;
    }

    /**
     * 点击事件
     * @param $blessing_id
     * @return bool
     * @throws Exception
     */
    public function click($blessing_id) {
        if (!$res = ($this->where(['id' => $blessing_id])->setInc('click_num'))) {
            self::$error_msg = '更新祝福失败';
            return false;
        }
        return true;
    }

    public function share($blessing_id) {
        if (!$this->where(['id' => $blessing_id])->setInc('share_num')) {
            self::$error_msg = '更新祝福失败';
            return false;
        }
        return true;
    }
}